import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:hui_location/hui_location.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = '';
  String locationString = '';
  String addressString = '';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    //String? locationString;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      if (kIsWeb) {
        _platformVersion = (await HuiLocation.platformVersion)!;
        setState(() {});
      } else {
        if (Platform.isAndroid) {
      /*    HuiLocation.locationData.then((value){
          });*/

          //定位分两组类型 gps(取gps定位) 与 net(取网络定位)
          HuiLocation().eventLocationData("gps").listen((event) {
            print(event!.longitude.toString());
            print(event.latitude.toString());
            locationString = "${event.longitude},${event.latitude}";
            HuiLocation().geocoderData(event.longitude!, event.latitude!).then((value){

              print(value!.addressLines);
              addressString = value.addressLines.toString();
            });
            setState(() {});
          });


        }
      }
    } catch (e) {
      print(e);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            initPlatformState();
          },
        ),
        body: Column(
          children: [
            Text('Running on: $_platformVersion\n'),
            Text('Running on: $locationString\n'),
            Text('解析地理位置: $addressString\n'),
          ],
        ),
      ),
    );
  }
}
